package cn.gjxblog.transaction;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 获取数据库连接的三种方式
 * 1、DriverManager
 * 2、DataSource
 * 3、数据库连接池
 */

public class GetConnectionTests {

    String url="jdbc:mysql://mysql.db.gjxblog.cn:3306/test";
    String name ="root";
    String pwd="123456";
    int port = 3306;
    String hostName = "mysql.db.gjxblog.cn";

    /**
     * 采用DriverManager
     */
    @Test
    public void test() throws ClassNotFoundException, SQLException {
        // 注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 获取连接
        for (int i = 0; i < 2000; i++) {
            Connection connection = DriverManager.getConnection(url, name, pwd);
            System.out.println(connection);
        }
    }

    /**
     * 采用DataSource方式
     */
    @Test
    public void test2() throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUser(name);
        ((MysqlDataSource) dataSource).setPassword(pwd);
        ((MysqlDataSource) dataSource).setServerName(hostName);
        ((MysqlDataSource) dataSource).setPort(port);
        for (int i = 0; i < 10; i++) {
            Connection connection = dataSource.getConnection();
            System.out.println(connection);

        }
    }

    /**
     * 采用数据连接池方式
     */
    @Test
    public void test3() throws SQLException {
        DataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver",url,name,pwd);
        ((PooledDataSource) dataSource).setPoolMaximumActiveConnections(2);
        for (int i = 0; i < 10; i++) {
            System.out.println(dataSource.getConnection());
        }
    }


}
